import React, { useState, useRef } from 'react';
import { Upload, Button, Card, message, Row, Col, Typography, Progress } from 'antd';
import { UploadOutlined, PlayCircleOutlined, PauseOutlined } from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd/es/upload/interface';

const { Title } = Typography;

interface AudioFile extends Omit<File, 'lastModified'> {
  lastModified: number;
  preview?: string;
  duration?: number;
  currentTime?: number;
  isPlaying?: boolean;
}

const AudioUpload: React.FC = () => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [audioFiles, setAudioFiles] = useState<Record<string, AudioFile>>({});
  const [loading, setLoading] = useState(false);
  const audioRefs = useRef<Record<string, HTMLAudioElement | null>>({});

  const beforeUpload = (file: AudioFile) => {
    const isAudio = file.type.startsWith('audio/');
    if (!isAudio) {
      message.error('只能上传音频文件!');
      return Upload.LIST_IGNORE;
    }
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.error('音频大小不能超过10MB!');
      return Upload.LIST_IGNORE;
    }

    // 创建音频预览
    const audio = new Audio();
    audio.src = URL.createObjectURL(file);
    
    audio.onloadedmetadata = () => {
      setAudioFiles(prev => ({
        ...prev,
        [file.name]: {
          ...file,
          duration: audio.duration,
          currentTime: 0,
          isPlaying: false,
        }
      }));
    };

    return false;
  };

  const handleChange: UploadProps['onChange'] = ({ fileList }) => {
    setFileList(fileList);
  };

  const togglePlay = (file: UploadFile) => {
    const audio = audioRefs.current[file.uid];
    const audioFile = audioFiles[file.name];

    if (!audio) return;

    if (audioFile?.isPlaying) {
      audio.pause();
    } else {
      audio.play();
    }

    setAudioFiles(prev => {
      const currentFile = prev[file.name];
      if (!currentFile) return prev;
      
      return {
        ...prev,
        [file.name]: {
          ...currentFile,
          isPlaying: !currentFile.isPlaying
        }
      };
    });
  };

  const handleTimeUpdate = (file: UploadFile) => {
    const audio = audioRefs.current[file.uid];
    if (!audio) return;

    setAudioFiles(prev => {
      const audioFile = prev[file.name];
      if (!audioFile) return prev;

      return {
        ...prev,
        [file.name]: {
          ...audioFile,
          currentTime: audio.currentTime,
          duration: audio.duration || audioFile.duration
        }
      };
    });
  };

  const handleEnded = (file: UploadFile) => {
    setAudioFiles(prev => {
      const currentFile = prev[file.name];
      if (!currentFile) return prev;
      
      return {
        ...prev,
        [file.name]: {
          ...currentFile,
          isPlaying: false,
          currentTime: 0
        }
      };
    });
  };

  const formatTime = (time: number = 0) => {
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
  };

  return (
    <div className="audio-upload">
      <Title level={4} style={{ marginBottom: 16 }}>音频上传</Title>
      <Card>
        <Row gutter={[16, 16]}>
          <Col span={24}>
            <Upload
              fileList={fileList}
              onChange={handleChange}
              beforeUpload={beforeUpload}
              accept="audio/*"
              multiple
            >
              <Button icon={<UploadOutlined />}>选择音频文件</Button>
            </Upload>
          </Col>
          
          <Col span={24}>
            <div className="audio-list">
              {fileList.map(file => {
                const audioFile = audioFiles[file.name];
                const progress = audioFile?.duration 
                  ? (audioFile.currentTime || 0) / audioFile.duration * 100 
                  : 0;

                return (
                  <div key={file.uid} className="audio-item" style={{ marginBottom: 16 }}>
                    <audio
                      ref={(el: HTMLAudioElement | null) => {
                        audioRefs.current[file.uid] = el;
                      }}
                      src={URL.createObjectURL(file.originFileObj as any)}
                      onTimeUpdate={() => handleTimeUpdate(file)}
                      onEnded={() => handleEnded(file)}
                      preload="metadata"
                      style={{ display: 'none' }}
                    />
                    <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
                      <Button
                        type="text"
                        icon={audioFile?.isPlaying ? <PauseOutlined /> : <PlayCircleOutlined />}
                        onClick={() => togglePlay(file)}
                        style={{ marginRight: 8 }}
                      />
                      <div style={{ flex: 1, marginRight: 8 }}>
                        <div>{file.name}</div>
                        <div style={{ fontSize: 12, color: '#999' }}>
                          {formatTime(audioFile?.currentTime)} / {formatTime(audioFile?.duration)}
                        </div>
                      </div>
                    </div>
                    <Progress 
                      percent={progress} 
                      showInfo={false}
                      strokeColor="#1890ff"
                    />
                  </div>
                );
              })}
            </div>
          </Col>

          <Col span={24}>
            <Button
              type="primary"
              onClick={() => {
                if (fileList.length === 0) {
                  message.warning('请先选择音频文件');
                  return;
                }
                setLoading(true);
                // 模拟上传
                setTimeout(() => {
                  setLoading(false);
                  message.success('上传成功');
                  setFileList([]);
                  setAudioFiles({});
                }, 1500);
              }}
              loading={loading}
              icon={<UploadOutlined />}
            >
              {loading ? '上传中...' : '开始上传'}
            </Button>
            <Button
              style={{ marginLeft: 8 }}
              onClick={() => {
                setFileList([]);
                setAudioFiles({});
                // 停止所有正在播放的音频
                Object.values(audioRefs.current).forEach(audio => {
                  if (audio) {
                    audio.pause();
                    audio.currentTime = 0;
                  }
                });
              }}
              disabled={fileList.length === 0}
            >
              清空
            </Button>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default AudioUpload;
